import CloudUploadIcon from '@material-ui/icons/CloudUpload';
import Button from '@material-ui/core/Button';
import React from "react";
import {ChangeEvent} from 'react';
import PictureUrl from "../components/PictureUrl";

const textStyle = {
  color: "#999",
  fontSize: "13px"
}

class PictureBed extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.manageUploadedFile = this.manageUploadedFile.bind(this);
    this.state = {pictureUrls: []}
  }

  getFileFromInput(file: File): Promise<any> {
    return new Promise(function (resolve, reject) {
      const reader = new FileReader();
      reader.onerror = reject;
      reader.onload = function () {
        resolve(reader.result);
      };
      reader.readAsBinaryString(file); // here the file can be read in different way Text, DataUrl, ArrayBuffer
    });
  }

  updatePictureUrl(jsonData: any) {
    let imageUrl = jsonData['data']['image_url']
    let urls: string[] = this.state.pictureUrls
    urls.push(imageUrl)
    this.setState({pictureUrls: urls})
    console.log(this.state.pictureUrls)
  }

  manageUploadedFile(binary: String, file: File) {
    console.log(`The file size is ${binary.length}`);
    console.log(`The file name is ${file.name}`);

    const url = "http://blog.yandage.top/v1/upload"

    const formData = new FormData();
    formData.append('file', file);
    fetch(url, {
      method: "post",
      body: formData,
      // mode: 'no-cors',
    }).then((res) => {
      res.json().then(r => {
        console.log(r)
        this.updatePictureUrl(r)
      })
    })
  }

  handleChange(event: ChangeEvent<HTMLInputElement>) {
    if (event.target.files === null) return;
    event.persist();
    Array.from(event.target.files).forEach(file => {
      this.getFileFromInput(file)
        .then((binary) => {
          this.manageUploadedFile(binary, file);
        }).catch(function (reason) {
        console.log(`Error during upload ${reason}`);
        event.target.value = ''; // to allow upload of same file if error occurs
      });
    });
  }

  render() {
    const urls: string[] = this.state.pictureUrls
    const listItems = urls.map((url) => <PictureUrl key={url} url={url}/>)

    const help = <div>
      <p style={textStyle}>如何使用：点击上传按钮，选择你要上传的图片即可</p>
      <p style={textStyle}>其它大小：在 url 后面增加 <code>size</code> 参数。 <code>size</code> 参数可以使用以下值<br/>
        <code>small</code>, <code>medium</code>, <code>large</code>, <code>phone</code>, 或自定义分辨率: 如<code>800x600</code><br/>
        示例1: <code>http://blog.yandage.top/v1/picture/42cf0c62-e3f6-5cd2-87b6-9d6c873cecbc.jpg?size=small</code><br/>
        示例2: <code>http://blog.yandage.top/v1/picture/42cf0c62-e3f6-5cd2-87b6-9d6c873cecbc.jpg?size=800x600</code></p>
    </div>

    return (
      <div style={{marginTop: "3em", marginBottom: "1em"}}>
        <h1>图床</h1>
        <input id={"contained-button-file"} type={"file"} name={"file"} accept={"image/*"}
               onChange={this.handleChange} style={{display: "none"}} multiple/>
        <label htmlFor="contained-button-file">
          <Button variant="contained" color="primary" component="span" startIcon={<CloudUploadIcon/>}>
            Upload
          </Button>
        </label>
        {help}
        <div style={{display: "flex", alignItems: "center", flexDirection: "column"}}>
          {listItems}
        </div>
      </div>
    );

  }
}

export default PictureBed;